<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="true" %>
<%
    // 在页面最顶部获取用户信息
    String username = (String) session.getAttribute("username");

    Integer userIdInt = (Integer) session.getAttribute("userId");
    String user_id = userIdInt != null ? userIdInt.toString() : "未知";

    String avatarUrl = (String) session.getAttribute("userAvatarUrl");

%>
<!DOCTYPE html>
<html>
<head>
    <title>购物车</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .cart-container {
            max-width: 1000px;
            margin: 20px auto;
            padding: 20px;
        }
        .cart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            height: 150px;
        }
        .cart-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .cart-table th, .cart-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .cart-table th {
            background-color: #f5f5f5;
        }
        .cart-total {
            text-align: right;
            font-size: 18px;
            margin-top: 20px;
        }
        .status-pending {
            color: #f0ad4e;
        }
        .status-completed {
            color: #5cb85c;
        }
        .status-cancelled {
            color: #d9534f;
        }
        .empty-cart {
            text-align: center;
            padding: 40px;
            color: #999;
        }
    </style>
</head>
<script>

    // 初始化加载订单
    document.addEventListener('DOMContentLoaded', () => {
        loadOrders();
    });
    function loadOrders() {
        fetch('cartServlet?action=getOrders')
            .then(response => response.json())
            .then(result => {
                if (result.status === 'success') {
                    console.log(result.orders);
                    displayOrders(result.orders);
                } else {
                    alert('获取订单失败：' + result.message);
                }
            }).catch(err => {
            console.log(err);
        });
    }

    // 渲染订单
    function displayOrders(orders) {
        const container = document.getElementById('ordersList');
        if (!orders || orders.length === 0) {
            container.innerHTML = '<div class="empty-cart"><h3>购物车是空的</h3><p>快去选购喜欢的商品吧！</p></div>';
            return;
        }

        let html = '<table class="cart-table">';
        html += ` <thead>
            <tr>
                <th>订单号</th>
                <th>商品名称</th>
                <th>金额</th>
                <th>状态</th>
                <th>下单时间</th>
            </tr>
        </thead>
        <tbody>
    `;

        let total = 0;
        orders.forEach(order => {
            const statusText = getStatusDisplay(order.status);
            const date = new Date(order.createdAt).toLocaleString();
            total += parseFloat(order.total);
            html += `
            <tr>
                <td>${order.id}</td>
                <td>${order.productName}</td>
                <td>￥${order.total}</td>
                <td><span class="status-${order.status}">${statusText}</span></td>
                <td>${date}</td>
            </tr>
        `;
        });

        html += '</tbody></table>';
        html += `<div class="cart-total">总计: ￥${total.toFixed(2)}</div>`;

        container.innerHTML = html;
    }

    // 状态显示函数
    function getStatusDisplay(status) {
        switch (status) {
            case 'pending': return '待付款';
            case 'completed': return '已完成';
            case 'cancelled': return '已取消';
            default: return status;
        }
    }

    const userId = <%= user_id %>;
    function goToPay(userId) {
        const totalElement = document.querySelector('.cart-total');
        if (!totalElement) {
            alert("购物车总计元素未找到！");
            return;
        }
        const totalText = totalElement.textContent;
        const totalAmount = parseFloat(totalText.replace('总计: ￥', '').trim());
        const orders = document.querySelectorAll('.cart-table tbody tr');
        const orderData = [];
        orders.forEach(order => {
            const orderId = order.cells[0].textContent;
            const productName = order.cells[1].textContent;
            const amount = order.cells[2].textContent.replace('￥', '');
            orderData.push({ orderId, productName, amount });
        });

        const productName = <%= username %>;

        const url = 'pay?totalAmount=' + encodeURIComponent(totalAmount) + '&shopName=' + encodeURIComponent(productName);

        fetch(url, { method: "GET" })
            .then(response => response.text()) // 获取支付宝返回的 HTML 表单
            .then(html => {
                // 创建新窗口
                const newWindow = window.open('', '_blank');
                newWindow.document.write(html); // 写入支付宝返回的表单
                newWindow.document.forms[0].submit(); // **自动提交表单**
            })
            .catch(error => console.error('Error:', error));
    }
</script>
<body>
<div class="cart-container">
    <div class="cart-header">
        <div>购物</div>
        <div style="display: flex;flex-direction: row;justify-content: center;">
            <h2>我的购物车</h2>
            <img src="<%= avatarUrl %>" alt="" style="border-radius: 50%;width: 150px;height: 150px;">
        </div>
    </div>

    <div id="ordersList">
        <!-- 动态加载订单 -->
    </div>
    <div>
        <button onclick="window.location.href='../index.jsp'" class="btn btn-primary">继续购物</button>
        <button onclick="goToPay(<%= user_id %>)" class="btn btn-primary">去支付</button>
    </div>
</div>
</body>
</html>
